package com.ruoyi.web.core.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.erp.domain.*;
import com.ruoyi.erp.service.*;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysOperLogService;
import org.apache.rocketmq.client.apis.*;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.consumer.FilterExpression;
import org.apache.rocketmq.client.apis.consumer.FilterExpressionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

@Component
public class RocketMqConsumer {

    @Value("${rocketmq.proxy}")
    private String proxy;//对应59.46.181.226:6891
	
	
    @Value("${rocketmq.consumer.group}")
    private String consumerGroup;//对应bzba_extend_yz_group
	
    @Value("${rocketmq.topic}")
    private String topic;//对应bac_fee_record
	
	@Value("${rocketmq.accesskey}")
    private String accesskey;//对应 rocketmq2
	
	@Value("${rocketmq.secretkey}")
    private String secretkey;//对应12345678
    @Autowired
    private ILedyBacFeeService ledyBacFeeService;
    @Autowired
    private ILedyUserClientService userClientService;
    @Autowired
    private ILedyFeeCheckinService checkinService;
    @Autowired
    private ILedyFeeRefundService refundService;
    @Autowired
    private ILedyOuterFeeCollectService collectService;
    @Autowired
    private ILedyOuterFeePayService payService;
    @Autowired
    private ILedyUserSimpleService simpleService;
    @Autowired
    private ISysOperLogService logService;

    @Bean(name = "MqConsumer")
    public void MqConsumer() {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
		
		SessionCredentialsProvider credentialsProvider =
                new StaticSessionCredentialsProvider(accesskey, secretkey);
		
       // 正确配置客户端（包含ACL认证）
        ClientConfiguration configuration = ClientConfiguration.newBuilder()
                .setEndpoints(proxy)
                .enableSsl(false)
                .setCredentialProvider(credentialsProvider)  // 添加ACL认证
                .build();
				
        // 初始化Producer时需要设置通信配置以及预绑定的Topic。
        try {
            log.info("构建mq5.0消费者：proxy:{}, topic:{}, group：{}", proxy, topic, consumerGroup);
            // 订阅消息的过滤规则，表示订阅所有Tag的消息。
            String tag = "*";
            FilterExpression filterExpression = new FilterExpression(tag, FilterExpressionType.TAG);
            provider.newPushConsumerBuilder()
                    .setClientConfiguration(configuration)
                    // 设置消费者分组。
                    .setConsumerGroup(consumerGroup)
                    // 设置预绑定的订阅关系。
                    .setSubscriptionExpressions(Collections.singletonMap(topic, filterExpression))
                    // 设置消费监听器。
                    .setMessageListener(messageView -> {
                        log.info("消费消息：{}", messageView); 
                        String message = StandardCharsets.UTF_8.decode(messageView.getBody()).toString();
                        log.info("接收到消息：" + message);
                        try {
                            jsonParse(message);
                            addLog(message, "bac_fee_record", 0, null);
                        } catch (Exception e) {
                            log.error("异常信息:{}", e.toString());
                            addLog(message, "bac_fee_record", 1, e.toString());
                        }
                        // 业务逻辑处理（成功返回 CONSUME_SUCCESS，失败返回 RECONSUME_LATER[3](@ref)）
                        return ConsumeResult.SUCCESS;
                    }).build();
            log.info("构建mq5.0消费者成功：proxy:{}, topic:{}, group：{}", proxy, topic, consumerGroup);
        } catch (ClientException e) {
            log.error("构建mq5.0消费者异常：proxy:{}, topic:{}, group：{}", proxy, topic, consumerGroup, e);
        }
    }
    private void addLog(String str, String topic, Integer status, String err) {
        SysOperLog log = new SysOperLog();
        log.setJsonResult(StringUtils.substring(str, 0, 5000));
        log.setBusinessType(0);
        log.setOperatorType(0);
        log.setStatus(status);
        log.setMethod("topic");
        log.setRequestMethod("kafka");
        log.setOperParam(topic);
        log.setErrorMsg(StringUtils.substring(err, 0, 5000));
        logService.insertOperlog(log);
    }

    @Transactional
    public void jsonParse(String str) throws Exception {
        BacFeeParam bacFeeParam = JSONUtil.toBean(str, BacFeeParam.class);
//            JSONObject json = JSONObject.parseObject(str);
        LedyBacFee ledyBacFee = JSONUtil.toBean(str, LedyBacFee.class);
//            LedyBacFee ledyBacFee = new LedyBacFee();
//            ledyBacFee.setRecordCode(json.getString("recordCode"));
//            ledyBacFee.setCaseCode(json.getString("caseCode"));
//            ledyBacFee.setRegisterNumber(json.getString("registerNumber"));
//            ledyBacFee.setGroupNumber(json.getJSONArray("groupNumber").toJSONString());
//            LedyUserSimple ledyUserClient = json.getObject("operator", LedyUserSimple.class);
//            checkUser(ledyUserClient);
//            ledyBacFee.setOperator(ledyUserClient.getUserCode());
//            LedyUserSimple acceptSecretary = json.getObject("acceptSecretary", LedyUserSimple.class);
//            checkUser(acceptSecretary);
//            ledyBacFee.setAcceptSecretary(acceptSecretary.getUserCode());
//            LedyUserSimple registerSecretary = json.getObject("registerSecretary", LedyUserSimple.class);
//            checkUser(registerSecretary);
//            ledyBacFee.setRegisterSecretary(registerSecretary.getUserCode());
//            LedyUserSimple handleSecretary = json.getObject("handleSecretary", LedyUserSimple.class);
//            checkUser(handleSecretary);
//            ledyBacFee.setHandleSecretary(handleSecretary.getUserCode());
//            LedyUserSimple lockedHandleSecretary = json.getObject("lockedHandleSecretary", LedyUserSimple.class);
//            checkUser(lockedHandleSecretary);
//            ledyBacFee.setLockedHandleSecretary(lockedHandleSecretary.getUserCode());
//            ledyBacFee.setEapRecordCode(json.getString("eapRecordCode"));
//            ledyBacFee.setRecordSchema(json.getString("recordSchema"));
        ledyBacFee.setRegisterSecretary("");
        ledyBacFee.setAcceptSecretary("");
        ledyBacFee.setHandleSecretary("");
        ledyBacFee.setLockedHandleSecretary("");
        if (ledyBacFee.getRecordSchema().equals("feeCheckIn")) {
//                LedyFeeCheckin recordDetail = json.getObject("recordDetail", LedyFeeCheckin.class);
            LedyFeeCheckin recordDetail = JSONUtil.toBean(ledyBacFee.getRecordDetail(), LedyFeeCheckin.class);
            if (recordDetail.getStatus() == 1) {
                BacFeeCheckin bacFeeCheckin = JSONUtil.toBean(ledyBacFee.getRecordDetail(), BacFeeCheckin.class);
                recordDetail.setAcceptNumber(ledyBacFee.getAcceptNumber());
                recordDetail.setRegisterNumber(ledyBacFee.getRegisterNumber());
                recordDetail.setOperator(bacFeeParam.getOperator().getRealName());
                recordDetail.setPayers(bacFeeCheckin.getPayers().stream().map(BacFeeCheckin.PayersBean::getRealName)
                        .collect(Collectors.joining(",")));
                recordDetail.setPayers(StringUtils.substring(recordDetail.getPayers(), 0, 100));
//                if("[1][6][0]".contains("["+ recordDetail.getClaimType() + "]")){
//                    recordDetail.setPayers(ledyBacFee.getp);
//                }else if("[2][3][7]".contains("["+ recordDetail.getClaimType() + "]")){
//
//                }else if("[4][5][8]".contains("["+ recordDetail.getClaimType() + "]")){
//
//                }
                recordDetail.setApplyUser("");
                recordDetail.setApproveUser("");
                recordDetail.setReceiptCodes("");
                recordDetail.setDocCodes("");
                recordDetail.setCheckinDocs("");
                recordDetail.setFallbackUser("");
                recordDetail.setConfirmUser("");
                recordDetail.setArbitratorList("");
                ledyBacFee.setRecordDetail("");
                ledyBacFeeService.insertLedyBacFee(ledyBacFee);
                checkinService.insertLedyFeeCheckin(recordDetail);
                ledyBacFee.setRecordDetail(recordDetail.getId().toString());

            }
        } else if (ledyBacFee.getRecordSchema().equals("feeRefund")) {
//                LedyFeeRefund recordDetail = json.getObject("recordDetail", LedyFeeRefund.class);
            LedyFeeRefund recordDetail = JSONUtil.toBean(ledyBacFee.getRecordDetail(), LedyFeeRefund.class);
            if (recordDetail.getStatus() == 2) {
                BacFeeRefund bacFeeRefund = JSONUtil.toBean(ledyBacFee.getRecordDetail(), BacFeeRefund.class);
                recordDetail.setAcceptNumber(ledyBacFee.getAcceptNumber());
                recordDetail.setRegisterNumber(ledyBacFee.getRegisterNumber());
                recordDetail.setLitigants(bacFeeRefund.getLitigants().stream().map(BacFeeRefund.LitigantsBean::getRealName)
                        .collect(Collectors.joining(",")));
                recordDetail.setLitigants(StringUtils.substring(recordDetail.getLitigants(), 0, 100));
                recordDetail.setRefundDocs("");
                recordDetail.setRefundOperateUser("");
                recordDetail.setApplyUser("");
                recordDetail.setApproveUser("");
                recordDetail.setSubmitFinanceUser("");
                recordDetail.setRefundAccount("");
                recordDetail.setReceiptCodes("");
                recordDetail.setDocCodes("");
                recordDetail.setOfficialDocCodes("");
                recordDetail.setStatData("");
                ledyBacFee.setRecordDetail("");
                ledyBacFeeService.insertLedyBacFee(ledyBacFee);
                refundService.insertLedyFeeRefund(recordDetail);
                ledyBacFee.setRecordDetail(recordDetail.getId().toString());

            }
        } else if (ledyBacFee.getRecordSchema().equals("outerFeeCollect")) {
//                LedyOuterFeeCollect recordDetail = json.getObject("recordDetail", LedyOuterFeeCollect.class);
            LedyOuterFeeCollect recordDetail = JSONUtil.toBean(ledyBacFee.getRecordDetail(), LedyOuterFeeCollect.class);
            if (recordDetail.getStatus() == 1) {
                if ("[3][1][0]".contains("[" + recordDetail.getFeeType() + "]")) {
                    BacFeeCheckin bacFeeCheckin = JSONUtil.toBean(ledyBacFee.getRecordDetail(), BacFeeCheckin.class);
                    recordDetail.setPayers(bacFeeCheckin.getPayers().stream().map(BacFeeCheckin.PayersBean::getRealName)
                            .collect(Collectors.joining(",")));
                    recordDetail.setPayers(StringUtils.substring(recordDetail.getPayers(), 0, 100));
                    recordDetail.setAcceptNumber(ledyBacFee.getAcceptNumber());
                    recordDetail.setRegisterNumber(ledyBacFee.getRegisterNumber());
                    recordDetail.setOperator(bacFeeParam.getOperator().getRealName());
                    recordDetail.setApplyUser("");
                    recordDetail.setApproveUser("");
                    recordDetail.setFeeDocs("");
                    recordDetail.setOutFeePayHistory("");
                    recordDetail.setCollector("");
                    LedyBacFee ledyBacFeeSerch = new LedyBacFee();
                    ledyBacFeeSerch.setRecordCode(ledyBacFee.getRecordCode());
                    List<LedyBacFee> ledyBacFeeList = ledyBacFeeService.selectLedyBacFeeList(ledyBacFeeSerch);
                    if (ledyBacFeeList != null && ledyBacFeeList.size() > 0) {
                        recordDetail.setId(Long.parseLong(ledyBacFeeList.get(0).getRecordDetail()));
                        collectService.updateLedyOuterFeeCollect(recordDetail);
                    } else {
                        collectService.insertLedyOuterFeeCollect(recordDetail);
                        ledyBacFee.setRecordDetail(recordDetail.getId().toString());
                        ledyBacFeeService.insertLedyBacFee(ledyBacFee);
                    }
                }
            }
        } else if (ledyBacFee.getRecordSchema().equals("outerFeePay")) {
            LedyOuterFeePay recordDetail = JSONUtil.toBean(ledyBacFee.getRecordDetail(), LedyOuterFeePay.class);
            if (recordDetail.getFeeStatus() == 2 || recordDetail.getFeeStatus() == 3) {
                BacFeeCheckin bacFeeCheckin = JSONUtil.toBean(ledyBacFee.getRecordDetail(), BacFeeCheckin.class);
                recordDetail.setPayers(bacFeeCheckin.getPayers().stream().map(BacFeeCheckin.PayersBean::getRealName)
                        .collect(Collectors.joining(",")));
                recordDetail.setPayers(StringUtils.substring(recordDetail.getPayers(), 0, 100));
                recordDetail.setAcceptNumber(ledyBacFee.getAcceptNumber());
                recordDetail.setRegisterNumber(ledyBacFee.getRegisterNumber());
                recordDetail.setOperator(bacFeeParam.getOperator().getRealName());
                recordDetail.setApplyUser("");
                recordDetail.setApproveUser("");
                recordDetail.setFeeDocs("");
                recordDetail.setAttachFiles("");
                recordDetail.setFeeListArray("");
                ledyBacFee.setRecordDetail("");
                ledyBacFeeService.insertLedyBacFee(ledyBacFee);
//                List<LedyFeePayDetail> recordPayDetail = JSONUtil.toBean(recordDetail.getDetails(), List<LedyFeePayDetail>.class);
                if (recordDetail.getDetails() != null && recordDetail.getDetails().size() > 0) {
                    recordDetail.getDetails().forEach(item -> {
                        LedyOuterFeePay recordDetails = new LedyOuterFeePay();
                        BeanUtil.copyProperties(recordDetail, recordDetails);
                        recordDetails.setPayers(StringUtils.substring(item.getRecordDetail().getPayers(), 0, 100));
                        recordDetails.setAmount(item.getPay());
                        recordDetails.setDetails(null);
                        payService.insertLedyOuterFeePay(recordDetails);
                    });
                } else {
                    recordDetail.setDetails(null);
                    payService.insertLedyOuterFeePay(recordDetail);
                }
                ledyBacFee.setRecordDetail(recordDetail.getId().toString());
            }
        }
//            ledyBacFee.setStatus(json.getLongValue("status"));
//            ledyBacFee.setInsertTime(json.getDate("insertTime"));
//            ledyBacFee.setUpdateTime(json.getDate("updateTime"));

    }
}